package com.loongtech.bi.action.system;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.loongtech.bi.advertisment.model.AdvWarnMacData;
import com.loongtech.bi.advertisment.service.PayUserService;
import com.loongtech.bi.support.ExcelUtils;

/**
 * 
 * ClassName: AdvWarningAction
 * 
 * @Description: 广告积分墙录入
 * @author liuchen
 * @date 2017-7-29 下午3:25:49
 */
@Controller("advWarningAction")
@Scope("view")
public class AdvWarningAction {

	List<AdvWarnMacData> datas;

	private AdvWarnMacData entity;

	@Resource(name = "payUserService")
	private PayUserService payUserService;

	@Autowired
	public void init() {
		search();
	}

	public void search() {
		datas = new ArrayList<>();
		try {
			datas = payUserService.getWarnMacData(null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private final String tmpuploaddir = "/usr/local/tomcat/upload/";
	private int uploadparamtype;
	private static File file;

	public void upload(FileUploadEvent event) throws IOException {
		System.out.println("upload file: ");
		UploadedFile ufile = event.getFile();
		if (ufile != null) {
			InputStream inputStream = ufile.getInputstream();

			File tmpdir = new File(tmpuploaddir);
			if (!tmpdir.exists()) {
				tmpdir.mkdir();
			}
			file = new File(tmpuploaddir + ufile.getFileName() + System.currentTimeMillis());
			file.createNewFile();

			OutputStream outputStream = new FileOutputStream(file);
			byte[] b = new byte[1024];
			while ((inputStream.read(b)) != -1) {
				outputStream.write(b);
			}
			inputStream.close();
			outputStream.close();
		}

		System.out.println("上传了文件：" + file == null ? file : file.getAbsolutePath());
	}

	public void parseExcel() {
		FacesContext context = FacesContext.getCurrentInstance();
		if (file != null && file.exists()) {
			try {
				List<AdvWarnMacData> tmp = parseUploadedExcel(file);
				List<AdvWarnMacData> list = payUserService.getWarnMacData(null);
				List<AdvWarnMacData> datas = new ArrayList<>();
				if (tmp != null && tmp.size() > 0) {
					if (list.size() > 0) {
						asd: for (AdvWarnMacData e : tmp) {
							for (AdvWarnMacData adv : list) {
								if (e.getMac().equals(adv.getMac())) {
									continue asd;
								} else {
									datas.add(e);
									continue asd;
								}
							}
						}
					} else {
						datas.addAll(tmp);
					}
				}
				payUserService.batchAddMac(datas);
			} catch (Exception e) {
				context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "解析文件错误！"));
				e.printStackTrace();
			} finally {
				if (file != null && file.exists()) {
					file.delete();
				}
			}
		} else {
			context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "请上传文件！"));
			return;
		}
	}

	private List<AdvWarnMacData> parseUploadedExcel(File file) throws Exception {
		List<AdvWarnMacData> result = new ArrayList<>();
		InputStream input = new FileInputStream(file);
		Workbook wb = WorkbookFactory.create(input);
		Sheet tempSheet = wb.getSheetAt(0);
		if (tempSheet == null) {
			IOUtils.closeQuietly(input);
			System.out.println("Error---------------------------excel内容为空,数据错误！");
			throw new Exception("excel内容为空,数据错误");
		}
		int rowNum = tempSheet.getLastRowNum();// 获得总行数
		for (int i = 0; i <= rowNum; i++) {
			Row row = tempSheet.getRow(i);
			if (row == null) {
				continue;
			}
			String mac = ExcelUtils.getCellValue(row.getCell(0));
			String kindtype = ExcelUtils.getCellValue(row.getCell(1));
			String source = ExcelUtils.getCellValue(row.getCell(2));

			if ("".equals(mac) || "".equals(kindtype) || "".equals(source)) {
				continue;
			}

			AdvWarnMacData e = new AdvWarnMacData();
			e.setMac(mac);
			e.setKindtype(kindtype);
			e.setSource(source);
			result.add(e);
		}
		IOUtils.closeQuietly(input);
		return result;
	}

	public List<AdvWarnMacData> getDatas() {
		return datas;
	}

	public void setDatas(List<AdvWarnMacData> datas) {
		this.datas = datas;
	}

	public int getUploadparamtype() {
		return uploadparamtype;
	}

	public void setUploadparamtype(int uploadparamtype) {
		this.uploadparamtype = uploadparamtype;
	}

	public static File getFile() {
		return file;
	}

	public static void setFile(File file) {
		AdvWarningAction.file = file;
	}

	public AdvWarnMacData getEntity() {
		return entity;
	}

	public void setEntity(AdvWarnMacData entity) {
		this.entity = entity;
	}
}
